package Presentation;

import Metier.Controleurs.GestionUtilisateur;
import Metier.Objets.Langue;
import Metier.Objets.Role;
import java.sql.SQLException;
import java.util.Locale;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JOptionPane;

/**
 * Fenêtre de connexion sur l'application, affiche la fenêtre principale si MDP OK
 */
public class FenetreConnexion extends javax.swing.JFrame {

    private final GestionUtilisateur gUtilisateur;
    
    /**
     * Creates new form FenetreConnexion
     */
    public FenetreConnexion() {
        this.gUtilisateur = new GestionUtilisateur();
        initComponents();
        // Centrer la fenetre
        this.setLocationRelativeTo(null);
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        lbl_motDePasse = new javax.swing.JLabel();
        lbl_role = new javax.swing.JLabel();
        btn_valider = new javax.swing.JButton();
        btn_annuler = new javax.swing.JButton();
        password_field = new javax.swing.JPasswordField();
        cbox_roles = new javax.swing.JComboBox();
        lbl_langue = new javax.swing.JLabel();
        cbox_langues = new javax.swing.JComboBox();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("GPB - Connexion");
        setBackground(new java.awt.Color(255, 255, 255));
        setModalExclusionType(java.awt.Dialog.ModalExclusionType.APPLICATION_EXCLUDE);

        lbl_motDePasse.setText("Mot de Passe :");

        lbl_role.setText("Rôle :");

        btn_valider.setText("Valider");
        btn_valider.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btn_validerActionPerformed(evt);
            }
        });

        btn_annuler.setText("Annuler");
        btn_annuler.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btn_annulerActionPerformed(evt);
            }
        });

        password_field.setToolTipText("Mot de passe");
        password_field.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                password_fieldKeyReleased(evt);
            }
        });

        cbox_roles.setModel(new DefaultComboBoxModel<>(Role.values()));
        cbox_roles.setToolTipText("Choisissez votre rôle");
        cbox_roles.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cbox_rolesActionPerformed(evt);
            }
        });

        lbl_langue.setText("Langue :");

        cbox_langues.setModel(new DefaultComboBoxModel<>(Langue.values()));
        cbox_langues.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cbox_languesActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(78, 78, 78)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(lbl_role)
                            .addComponent(lbl_motDePasse)
                            .addComponent(lbl_langue))
                        .addGap(70, 70, 70)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(password_field)
                            .addComponent(cbox_roles, 0, 195, Short.MAX_VALUE)
                            .addComponent(cbox_langues, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(124, 124, 124)
                        .addComponent(btn_valider)
                        .addGap(76, 76, 76)
                        .addComponent(btn_annuler)))
                .addContainerGap(85, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addGap(71, 71, 71)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(lbl_role)
                    .addComponent(cbox_roles, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(62, 62, 62)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(lbl_motDePasse)
                    .addComponent(password_field, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 60, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(lbl_langue, javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(cbox_langues, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(50, 50, 50)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btn_valider)
                    .addComponent(btn_annuler))
                .addGap(38, 38, 38))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void btn_annulerActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btn_annulerActionPerformed
        System.exit(0);
    }//GEN-LAST:event_btn_annulerActionPerformed

    private void btn_validerActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btn_validerActionPerformed
        char[] pass = this.password_field.getPassword();
        Role role = (Role)this.cbox_roles.getSelectedItem();
        Langue l = (Langue)cbox_langues.getSelectedItem();
        Locale locale = l.getLocale();
        if (pass.length < 1) {
            JOptionPane.showMessageDialog(this,
                    "Veuillez remplir le champ mot de passe !",
                    "Message d'erreur",
                    JOptionPane.ERROR_MESSAGE);       
        } else {
            try {
                if (this.gUtilisateur.connexion(role, pass)) {
                    // Ouvrir la fenetre principale
                    FenetrePrincipale fPrincipale = new FenetrePrincipale(this, role, locale);
                    this.setVisible(false);
                    fPrincipale.setVisible(true);
                } else {
                    JOptionPane.showMessageDialog(this,
                            "Mauvais mot de passe, veuillez réessayer",
                            "Message d'erreur",
                            JOptionPane.ERROR_MESSAGE);
                }
            } catch (SQLException e) {
                JOptionPane.showMessageDialog(this,
                        "Problème de connexion avec la base de donnée. Vérifiez votre connexion internet",
                        "Message d'erreur",
                        JOptionPane.ERROR_MESSAGE);
            } finally {
                this.password_field.setText("");
            }
        }
    }//GEN-LAST:event_btn_validerActionPerformed

    private void cbox_rolesActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cbox_rolesActionPerformed
        
    }//GEN-LAST:event_cbox_rolesActionPerformed

    private void password_fieldKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_password_fieldKeyReleased
        if(evt.getKeyCode() == java.awt.event.KeyEvent.VK_ENTER){
            btn_valider.doClick();
        }
    }//GEN-LAST:event_password_fieldKeyReleased

    private void cbox_languesActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cbox_languesActionPerformed
        
    }//GEN-LAST:event_cbox_languesActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(FenetreConnexion.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(FenetreConnexion.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(FenetreConnexion.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(FenetreConnexion.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                new FenetreConnexion().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btn_annuler;
    private javax.swing.JButton btn_valider;
    private javax.swing.JComboBox cbox_langues;
    private javax.swing.JComboBox cbox_roles;
    private javax.swing.JLabel lbl_langue;
    private javax.swing.JLabel lbl_motDePasse;
    private javax.swing.JLabel lbl_role;
    private javax.swing.JPasswordField password_field;
    // End of variables declaration//GEN-END:variables
}
